package com.chaoli.reggie_diy.filter;

import com.alibaba.fastjson.JSON;
import com.chaoli.reggie_diy.common.BaseContext;
import com.chaoli.reggie_diy.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 检查登录状态
 */
@Slf4j
@WebServlet(urlPatterns = "/*")
@Component
public class LoginCheckFilter implements Filter {

    public static final AntPathMatcher ANT_PATH_MATCHER = new AntPathMatcher();

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        //获取本次请求的uri
        String requestURI = request.getRequestURI();
        log.info("拦截到请求:{}",requestURI);

        //定义请求白名单
        String[] urls = new String[]{
                "/employee/login",
                "/employee/logout",
                "/backend/**",
                "/front/**",
                "/common/**",
                "/user/sendMsg", // 移动端发送短信
                "/user/login" // 移动端登录
        };

        //检查请求路径是否需要处理
        boolean check = check(urls, requestURI);
        //如果是白名单，则不需要处理
        if (check) {
            log.info("本次 {} 请求不需要处理", requestURI);
            filterChain.doFilter(request, response);
            return;
        }

        //不在白名单内，请求需要被处理

        // 网页端登录
        //判断登录状态，如果已经登录，则放行
        if (request.getSession().getAttribute("employee") != null) {
            log.info("线程id为：" + Thread.currentThread().getId());
            Long empId = (Long) request.getSession().getAttribute("employee");
            log.info("用户已登录，用户id为:{}", empId);
            BaseContext.setCurrentId(empId);
            filterChain.doFilter(request, response);
            return;
        }

        //移动端登录
        //判断登录状态，如果已经登录，则放行
        if (request.getSession().getAttribute("user") != null) {
            Long userId = (Long) request.getSession().getAttribute("user");
            log.info("用户已登录，用户id为：{}",userId);
            BaseContext.setCurrentId(userId);
            filterChain.doFilter(request, response);
            return;
        }

        log.info("用户未登录");
        //因为是空返回值，所以要用输出流的方式给前端页面返回数据
        response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
    }

    /**
     * 路径匹配
     * @param urls 白名单
     * @param requestURI 请求路径
     * @return true表示符合白名单直接放行，false表示不符合白名单需要过滤
     */
    public boolean check(String[] urls, String requestURI) {
        for (String url : urls) {
            boolean match = ANT_PATH_MATCHER.match(url, requestURI);
            if (match) {
                return true;
            }
        }
        return false;
    }
}
